﻿using System;
using System.Collections.Generic;
using System.IO;
using ooWii.Security;

namespace ooWii.Collections
{
	public class CertificateChain : Dictionary<string, PublicKey>
	{
		#region CertificateChain

		IList<PublicKey> childKeys = new List<PublicKey>();

		public static CertificateChain Create( Stream stream, SHA1Engine sha1Engine )
		{
			CertificateChain certificateChain = new CertificateChain();

			RSAEngine rsaEngine = new RSAEngine();

			certificateChain.Add( "Root", new RootKey( rsaEngine, sha1Engine ) );

			while( stream.Position < stream.Length )
			{
				PublicKey publicKey = PublicKey.Create( rsaEngine, sha1Engine, stream );

				certificateChain.childKeys.Add( publicKey );
				certificateChain.Add( publicKey.Identity, publicKey );
			}

			return certificateChain;
		}

		public void VerifySignature()
		{
			for( int i = 0; i < childKeys.Count; i++ )
			{
				PublicKey publicKey = childKeys[ i ];

				PublicKey issuerPublicKey;
				if( !TryGetValue( publicKey.Issuer, out issuerPublicKey ) )
				{
					throw new WiiException( "Certificate chain issuer not found" );
				}

				if( !issuerPublicKey.VerifySignature( publicKey.Bytes, publicKey.Signature ) )
				{
					throw new WiiException( "Certificate chain signature check failed" );
				}
			}
		}

		#endregion
	}
}
